﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Hosting;

namespace Ymatou.File.Lib
{
    public static class FileTool
    {
        private static string SourceTypeSeprator
        {
            get { return "_"; }
        }

        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="requestBase"></param>
        /// <param name="fileFullPath"></param>
        public static void SaveFile(Stream inputStream, string fileFullPath)
        {
            if (System.IO.File.Exists(fileFullPath))
            {
                //throw new Exception("已存在相同的文件名");
                //同名覆盖
                System.IO.File.Delete(fileFullPath);
            }

            string directory = Path.GetDirectoryName(fileFullPath);

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            //获得上传文件流
            using (Stream uploadStream = inputStream)
            {
                //保存上传的文件
                using (FileStream fileStream = System.IO.File.Create(fileFullPath))
                {
                    try
                    {
                        int bufSize = 1024;
                        int byteGet = 0;
                        byte[] buf = new byte[bufSize];
                        while ((byteGet = uploadStream.Read(buf, 0, bufSize)) > 0)
                        {
                            fileStream.Write(buf, 0, byteGet);
                            fileStream.Flush();
                        }
                    }
                    catch (Exception ex)
                    {
                        throw;
                    }
                }

                uploadStream.Close();
            }
        }


        /// <summary>
        /// 可以按照不同类型生成不同的保存规则
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="fileType">暂时没有使用</param>
        /// <returns>新命名的文件</returns>
        public static string GenerateFileName(string fileName)
        {
            string ext = Path.GetExtension(fileName);

            //使用GUID作为文件名
            string guid = Guid.NewGuid().ToString();
            return guid + ext;
        }

        public static string GetPhysicalFolder(string type, string source = "")
        {
            if (!string.IsNullOrEmpty(source))
            {
                return (type + SourceTypeSeprator + source).ToLower();
            }

            return type.ToLower();
        }

        public static string GetAndGeneratePhysicalFolder(string type, string source = "")
        {
            string virtualFolder = type;

            if (!string.IsNullOrEmpty(source))
            {
                virtualFolder = type + SourceTypeSeprator + source;
            }

            string directoryPath = Path.Combine(FileHelper.PhysicalBasePath, virtualFolder);


            DirectoryInfo folderInfo = new DirectoryInfo(directoryPath);
            if (!folderInfo.Exists)
            {
                folderInfo.Create();
            }

            return virtualFolder;
        }

        public static string GenerateAccessUrl(string virtualPath)
        {
            //生成访问路径
            string domain = FileHelper.FileAccessDomain;

            string accessRoute = FileHelper.AccessRoute;

            //返回文件生成路径
            return domain + "/" + accessRoute + "/" + virtualPath.Replace("\\", "/");
        }

        public static string GetTypeSource(string wholeType, out string source)
        {
            source = string.Empty;
            if(!string.IsNullOrEmpty(wholeType))
            {
                wholeType = wholeType.ToLower();
                int sepratorIndex = wholeType.LastIndexOf(SourceTypeSeprator);
                if(sepratorIndex <= 0)
                {
                    return wholeType;
                }
                else
                {
                    source = wholeType.Substring(sepratorIndex + 1, wholeType.Length - sepratorIndex - 1);
                    return wholeType.Substring(0, sepratorIndex);
                }
            }
            else
            {
                return wholeType;
            }
        }

        public static bool ValidateRefUrl(string type, HttpRequestBase request)
        {
            bool validate = false;
            string source = string.Empty;
            if (!string.IsNullOrEmpty(type) && GetTypeSource(type, out source) == "idcard")
            {
                if(request.UrlReferrer == null)
                {
                    return false;
                }
                else
                {
                    return ValidateIdCardRefUrl(request.UrlReferrer.AbsoluteUri);
                }
            }
            else
            {
                validate = true;
            }

            return validate;
        }

        /// <summary>
        /// 根据请求来源判定
        /// </summary>
        /// <param name="type"></param>
        /// <param name="currentRefUrl"></param>
        /// <returns></returns>
        public static bool ValidateIdCardRefUrl(string currentRefUrl)
        {
            if(string.IsNullOrEmpty(currentRefUrl))
            {
                return true;
            }
            else
            {
                currentRefUrl = currentRefUrl.ToLower();
            }


            bool validate = false;
            string source = string.Empty;
            
            string validatedUrl = ConfigurationManager.AppSettings["IdCardRefUrlPrefix"];

            if(!string.IsNullOrEmpty(validatedUrl))
            {
                string[] validatedUrlRefs = validatedUrl.Split(new string[] {","},
                                                                StringSplitOptions.RemoveEmptyEntries);

                foreach(string urlPrefix in validatedUrlRefs)
                {
                    if(currentRefUrl.StartsWith(urlPrefix.ToLower()))
                    {
                        validate = true;
                        break;
                    }
                }
            }
            else
            {
                validate = true;
            }
           

            return validate;
        }
    }
}